/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.datacenter.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.cshoo.tattoo.datacenter.api.dto.AddTemplateReq;
import org.cshoo.tattoo.datacenter.api.dto.QueryTemplateResp;
import org.cshoo.tattoo.datacenter.api.dto.UpdateTemplateReq;
import org.cshoo.tattoo.datacenter.api.dto.ValidResp;
import org.cshoo.tattoo.datacenter.app.TemplateAppService;
import org.cshoo.tattoo.embed.infra.entity.FileEntity;
import org.cshoo.tattoo.embed.infra.entity.PageQueryEntity;
import org.cshoo.tattoo.embed.infra.entity.Response;
import org.cshoo.tattoo.embed.infra.exception.ValidateException;
import org.springframework.data.domain.Page;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author 杨翼
 * @since 1.0
 */
@Api(tags = "Template接口")
@RestController
@RequestMapping(value = "/template")
@Slf4j
public class TemplateController {

    @Resource
    private TemplateAppService templateAppService;

    @ApiOperation("校验message编号")
    @RequestMapping(value = "/checkTemplateCodeExists", method = RequestMethod.GET)
    public ValidResp checkTemplateCodeExists(@RequestParam String code) {
        ValidResp result = new ValidResp();
        boolean exists = templateAppService.checkTemplateCodeExists(code);
        result.setValid(!exists);
        return result;
    }

    @ApiOperation("添加template")
    @PostMapping(value = "/addTemplate")
    public Response<?> addTemplate(@RequestBody AddTemplateReq addTemplateReq) throws ValidateException {
        log.info("addTemplateReq:{}", addTemplateReq);
        templateAppService.addTemplate(addTemplateReq);
        return Response.builder().build();
    }

    @ApiOperation("删除template")
    @DeleteMapping(value = "/deleteTemplate/{id}")
    public Response<?> deleteTemplate(@PathVariable("id") Long id) {
        templateAppService.deleteTemplate(id);
        return Response.builder().build();
    }

    @ApiOperation("修改template")
    @PutMapping(value = "/updateTemplate")
    public Response<?> updateTemplate(@RequestBody UpdateTemplateReq updateTemplateReq) throws ValidateException {
        templateAppService.updateTemplate(updateTemplateReq);
        return Response.builder().build();
    }

    @ApiOperation("查询template")
    @PostMapping(value = "/page/queryTemplates")
    public Page<QueryTemplateResp> queryTemplates(@RequestBody PageQueryEntity<String> pageReqEntity) {
        return templateAppService.queryTemplates(pageReqEntity);
    }

    @ApiOperation("根据编号查询单个template")
    @GetMapping(value = "/querySingleTemplate/{code}")
    public QueryTemplateResp querySingleTemplate(@PathVariable("code") String code) {
        return templateAppService.querySingleTemplate(code);
    }

    @ApiOperation("上传模板文件")
    @PostMapping(value = "/uploadTemplateFile")
    public Response<?> uploadTemplateFile(@RequestParam("file") MultipartFile file) throws IOException {
        String fileStoreName = templateAppService.uploadTemplateFile(file);
        return Response.builder().data(fileStoreName).build();
    }

    @ApiOperation("下载模板文件")
    @GetMapping(value = "/downloadTemplateFile/{fileStoreName}")
    public ResponseEntity<StreamingResponseBody> downloadTemplateFile(@PathVariable("fileStoreName") String fileStoreName) throws IOException, ValidateException {
        FileEntity fileEntity = templateAppService.downloadTemplateFile(fileStoreName);
        File file = fileEntity.getFile();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(file.length());
        String encodedFileName = URLEncoder.encode(fileEntity.getName(), StandardCharsets.UTF_8.name());
        ContentDisposition contentDisposition = ContentDisposition.attachment().filename(encodedFileName).build();
        headers.setContentDisposition(contentDisposition);
        StreamingResponseBody responseBody = outputStream -> {
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, outputStream);
            }
        };

        return ResponseEntity.ok().headers(headers).body(responseBody);
    }
}
